// counterStore.js
import { shallowRef, markRaw, shallowReactive, toRaw, isRef, readonly,isProxy } from 'vue'
import { defineStore } from 'pinia'
import FormItem from '@/components/vue-flow/nodes/formItem.vue'
import { PlusIcon, AlertCircleIcon, ChevronDown, Minus, Braces, MinusCircleIcon } from 'lucide-vue-next'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
import { Button } from '@/components/ui/button'
import Holder from '@/components/vue-flow/nodes/holder.vue'
import { dict } from '@/lib/dict.ts'
import SelectComponent from '@/components/vue-flow/nodes/selectComponent.vue'
import {cloneDeep} from 'lodash'
const template = {
  "id": "selector_1",
  "type": "selector",
  "data": {
    "title": "选择器节点",
    "description": '连接多个下游分支，若设定的条件成立则仅运行对应的分支，若均不成立则只运行“否则”分支',
    "properties": {
      "json": {
        "icon": 'MinusCircleIcon',
        "size": 16,
        "color": 'rgb(28 31 35 / 15%)'
      }
    },
    "labels": [
      { "label": '引用变量', "key": 'referenceVariable' },
      { "label": '选择条件', "key": 'condition' },
      { "label": '比较值', "key": 'compareValue' },
    ],
    "branchs": [
      {
        "id":"if-0",
      "conditions": [{
        "left": {
          "ref": "",
          "category": "1",
          "value": "outputText"
        },
        "relational": "eq",
        "right": {
          "ref": "",
          "category": "1",
          "value": "output.data.suggestions[0].category.name"
        }
      },
        ],
        "logical": "and",
        "transition": "edge_4"
      },
    ],
    "transition": "edge_5"
  }
}

interface Condition {
  [key: string]: any; // 如果你知道具体类型，替换 `any`
}

interface Branch {
  conditions: Condition[];
}

export const useIfStore = defineStore({
  id: 'useIfStore',
  state: () => ({
    nodes:[],
    ids:[],
  }),
  actions: {
    init(data:any){
      this.nodes=[]
      this.nodes.push(data)
      this.ids.push(data.id)
    },    
    setId(id:string){
      const target ={
        "id": "selector_1",
        "type": "selector",
        "data": {
          "title": "选择器节点",
          "description": '连接多个下游分支，若设定的条件成立则仅运行对应的分支，若均不成立则只运行“否则”分支',
          "properties": {
            "json": {
              "icon": 'MinusCircleIcon',
              "size": 16,
              "color": 'rgb(28 31 35 / 15%)'
            }
          },
          "labels": [
            { "label": '引用变量', "key": 'referenceVariable' },
            { "label": '选择条件', "key": 'condition' },
            { "label": '比较值', "key": 'compareValue' },
          ],
          "branchs": [
            {
              "id":"if-0",
            "conditions": [{
              "left": {
                "ref": "",
                "category": "1",
                "value": ""
              },
              "relational": "eq",
              "right": {
                "ref": "",
                "category": "1",
                "value": ""
              }
            },
              ],
              "logical": "and",
              "transition": ""
            },
          ],
          "transition": ""
        }
      }
      this.ids.push(id)
      this.nodes.push(cloneDeep(target))
      this.nodes.length && (this.nodes[this.nodes.length - 1].id = id);
    },
    addCondition(index:number,id:string) {
      const indexVal = this.nodes.findIndex((el:any) => el.id == id)
      this.nodes[indexVal].data.branchs[index].conditions.push({
          "left": {
            "ref": "",
            "category": "1",
            "value": ""
          },
          "relational": "eq",
          "right": {
            "ref": "",
            "category": "1",
            "value": ""
          }
        })
    },
    addNode(){
    },
    add(id:string) {
      // template.data.branchs.push(
      //   {
      //     "conditions": [{
      //       "left": {
      //         "ref": "",
      //         "category": "1",
      //         "value": "outputText"
      //       },
      //       "relational": "eq",
      //       "right": {
      //         "ref": "",
      //         "category": "1",
      //         "value": "output.data.suggestions[0].category.name"
      //       }
      //     },
      //     ],
      //     "logical": "and",
      //     "transition": ""
      //   }
      // )
      // const newTemplate = cloneDeep(template);
      // this.nodes.push(newTemplate)
      const temp = 
      this.nodes.forEach((el:any,index:number) => {
        if(el.id == id)
        el.data.branchs.push({
          "id":'if-else-'+el.data.branchs.length,
          "conditions": [{
            "left": {
              "ref": "",
              "category": "1",
              "value": ""
            },
            "relational": "eq",
            "right": {
              "ref": "",
              "category": "1",
              "value": ""
            }
          }]
        })
      });
    },
    getindexVal(id:string){
      return  this.nodes.findIndex((el:any) => el.id == id);
    },
    getBranchIndex(branchsItemId:string,id:string){
      const indexVal = this.getindexVal(id)
      return  this.nodes[indexVal].data.branchs.findIndex((item:any) => item.id === branchsItemId);
    },
    removeItem(branchsItemId:string, id:string) {
      const indexVal = this.getindexVal(id)
      console.log(branchsItemId,id,indexVal,'branchsItemId,idbranchsItemId,idbranchsItemId,idbranchsItemId,id')
      if (indexVal !== -1) {
        const branchIndex = this.getBranchIndex(branchsItemId,id)
        if (branchIndex !== -1) {
          this.nodes[indexVal].data.branchs.splice(branchIndex, 1);
          this.nodes[indexVal].data.branchs.forEach((element,index) => { //更新id
            element.id = element.id.replace(/(.*)-2$/, `$1-${index}`)
          });
        }
      }
    },
    deleteItemCondition(index:number,conditionsIndex:number,id:string) {
      const indexVal = this.nodes.findIndex((el:any) => el.id == id)
      this.nodes[indexVal].data.branchs[index].conditions.splice(conditionsIndex, 1)
    },
    // setOptions(Options:any) {
    //   let RawOptions;
    //   if(isProxy(Options)){
    //     RawOptions = toRaw(Options)
    //   }else{
    //     RawOptions = Options;
    //   }
    //   const defaultValue = RawOptions.value[0]?.label;
    //   this.template.data.branchs.forEach(item=>{
    //     item.conditions.forEach(item=>{
    //       item.left.value =defaultValue
    //       item.left.ref=RawOptions.value[0]?.id;
    //       item.right.ref=RawOptions.value[0]?.id;
    //       item.right.value =defaultValue
    //     })
    //   }) 
    // },
    updateInputValue(index: number, outputKey: string, conditionsIndex: number, val: string,id:string) {
      const key = outputKey.split('.');
      const indexVal = this.nodes.findIndex((el:any) => el.id == id)
      const branch = this.nodes[indexVal].data.branchs[index];
      const condition:Condition = branch.conditions[conditionsIndex];
      if (key.length > 1) {
        // 访问嵌套对象
        (condition[key[0]] as any)[key[1]] = val; // 你可以替换 `any` 为具体类型
      } else {
        condition[key[0]] = val;
      }
    },
    setTransition(edgeObj:{leftRef:string,leftTransition:string,rightRef:string,rightTransition:string,id:string,type:string}){ //处理边
      const {leftRef='',rightRef='',rightTransition='',id='',type} = edgeObj
      const index = this.nodes.findIndex((el:any) => el.id == id)
      if(type=='if'){
        console.log(rightTransition,'rightTransition')
        this.nodes[index].data.branchs.forEach((el:any) => {
          el.transition = rightTransition;
          el.conditions.forEach((condition:any) => {
            condition.left.ref = leftRef;
            condition.right.ref = rightRef;
          });
        });
      }else{
        console.log(rightTransition,'rightTransition')
        this.nodes[index].data.transition = rightTransition;
      }
    },
    updateRef(id:string){
      console.log(id,'-------------')
      // this.nodes = toRefs([...nodes])
    }
  }
})
